const express= require("express");
const router=express.Router();
const db=require("../model/db");
//添加院线  作者：傅业薪
router.post("/",async (req,res)=>{
    const data=  await db.Cinema.create(req.body);
    res.send({
        "code": 0,
        "message": "",
        "data":  data
    });
})

//得到所有院线  作者：傅业薪
//修改  加分页  排序
router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //分页
    if (!req.query.page) {
        req.query.page = 1;
    }
    if (!req.query.limit) {
        req.query.limit = 10;
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition={};
    if(req.query.key){
        const exp=new RegExp(req.query.key,"i");
        condition={
            $or:[
                {name:{$regex:exp}},
                {tel:{$regex:exp}},
                {addr:{$regex:exp}}
            ]        
        };
    }
    const data = await db.Cinema.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    const count = await db.Cinema.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})

//得到单个院线 作者：傅业薪
router.get("/:id",async (req,res)=>{
    const data=await db.Cinema.findOne({
        _id:req.params.id
    })
    res.send({
        "code": 0,
        "message": "",
        "data":  data
    });

})
//作者：廖慧
//修改影院
router.put("/:id", async (req, res) => {
   await db.Cinema.updateOne({ _id: req.params.id }, req.body)
    res.send(true);
  });

//删除院线 作者：傅业薪
router.delete("/:id",async(req,res)=>{
   await  db.Cinema.deleteOne({
        _id:req.params.id
     })

     res.send({
        "code": 0,
        "message": "",
        "data":  "true"
    });
})

module.exports=router;